#!/usr/local/bin/python3

import threading
import time
import sys
import signal

class Memory:
    def __init__(self):
        self.direcciones= []
        
    def get(self, index):
        return self.direcciones[index]
    
    def set(self, index,instruction):
        self.direcciones.insert(index, instruction)
        
    def setLista(self, lista):
        self.direcciones.extend(lista)
        
    def getLastIndex(self):
        return len (self.direcciones)
        
class MemoryManager:
    def __init__(self,memoria):
        self.memoria = memoria
        self.primerCeldaGuardada = 0
        self.ultimaCeldaGuardada = 0
    
    def guardarEnMemoria(self, program):
        self.primerCeldaGuardada = self.ultimaCeldaGuardada
        for instruccion in program.getInstrucciones():
            self.memoria.set(self.ultimaCeldaGuardada,instruccion)
            self.ultimaCeldaGuardada = self.ultimaCeldaGuardada + 1
        
    def getPrimeraCeldaGuardada(self):
        return self.primerCeldaGuardada
    
    def getUltimaCeldaGuardada(self):
        return self.ultimaCeldaGuardada
    
    def get(self, index):
        return self.memoria.get(index)

class Clock(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.listeners = []
    
    def run(self):
        self.timing()

    def register(self, cpu):
        self.cpu = cpu

    def notify_listeners(self, event):
            self.cpu.tick(event)

    def timing(self):
        while True:
            print('Clock Tick tock !')
            self.notify_listeners(self)
            time.sleep(2)
            #sys.stdout.flush()

class CPU(threading.Thread):    
    def __init__(self, clock, quantum, memoryManager):
        threading.Thread.__init__(self)
        self.quantum = quantum
        self.memoryManager = memoryManager
        clock.register(self)
    
    def setPCB(self,pcb):
        self.pcb = pcb
    
    def getPCB(self):
        return self.pcb

    def tick(self, event):
        print('CPU Tick tock !')
#        pcb = self.getPCB()
        for i in range(self.quantum):
            print(i)
#           pcb.getInstruccion.correr(ioHandler)
#        ioHandler.timeOutHandler(self.getPCB())
#        pcb.incrementarPC()
        
    
#        instruccion = self.memoryManager.get(pcb.getInstruccionEjecutar())

 
#    def correrIntruccion(self,instruccion):
#        self.ioHandler.

memory = Memory()
memoryManager = MemoryManager(memory)
clock = Clock()
cpu = CPU(clock,5000,memoryManager)
cpu.start()
clock.start()




